package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.*;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    CheckGroupMapper checkGroupMapper;
    @Autowired
    CheckItemMapper checkItemMapper;
    @Autowired
    SetmealGroupMapper setmealGroupMapper;
    @Autowired
    private Configuration configuration;

    /**
     * 添加套餐
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    public void add(Setmeal setmeal, ArrayList<Integer> checkgroupIds) {
        setmealMapper.insert(setmeal);

        //分离并添加图片名到Redis缓存中
        String[] split = setmeal.getImg().split("/");
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,split[split.length - 1]);

        if(checkgroupIds != null && checkgroupIds.size() > 0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealGroupMapper.insert(setmeal.getId(),checkgroupId);
            }
        }

        //生成静态页面
        generateStaticPages();
    }

    /**
     * 生成静态页面
     */
    private void generateStaticPages() {
        // 查询所有套餐数据
        List<Setmeal> setmealList = setmealMapper.findAll();

        for (Setmeal setmeal : setmealList) {
            //根据套餐id查询检查组信息
            ArrayList<CheckGroup> checkGroups = checkGroupMapper.findBySetmealId(setmeal.getId());
            //根据检查组id查询检查项信息
            for (CheckGroup checkGroup : checkGroups) {
                ArrayList<CheckItem> checkItems = checkItemMapper.findByCheckGroupId(checkGroup.getId());
                checkGroup.setCheckItems(checkItems);
            }
            setmeal.setCheckGroups(checkGroups);
        }

        // 生成套餐列表页面
        generateSetmealListPage(setmealList);

        // 生成套餐详情页面
        generateSetmealDetailPages(setmealList);
    }

    /**
     * 生成套餐列表页面
     * @param setmealList
     */
    private void generateSetmealListPage(List<Setmeal> setmealList) {
        try {

            Template template = configuration.getTemplate("mobile_setmeal.ftl");

            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("setmealList", setmealList);

            Writer writer = new FileWriter(new File("bxg-health-mobile/src/main/resources/mobile/pages/setmeal1.html"));
            template.process(dataModel, writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成套餐详情页面
     * @param setmealList
     */
    private void generateSetmealDetailPages(List<Setmeal> setmealList) {
        try {

            for (Setmeal setmeal : setmealList) {
                Map<String, Object> detailModel = new HashMap<>();
                detailModel.put("setmeal", setmeal);

                Template detailTemplate = configuration.getTemplate("mobile_setmeal_detail.ftl");
                Writer detailWriter = new FileWriter(new File("bxg-health-mobile/src/main/resources/mobile/pages/setmeal_detail_" + setmeal.getId() + ".html"));
                detailTemplate.process(detailModel, detailWriter);
                detailWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 修改套餐
     * @param setmeal
     * @param checkGroupIds
     */
    @Transactional
    public void update(Setmeal setmeal, ArrayList<Integer> checkGroupIds) {
        //若修改了图片，则将其添加到redis中
        if (setmeal.getImg() != null){
            //删除Redis中套餐图片名
            detelePictureRedisBySetmealId(setmeal.getId());
            //添加到Redis中
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }

        setmealMapper.update(setmeal);

        //删除套餐和检查组关系，添加修改后的套餐和检查组关系
        if (checkGroupIds != null && checkGroupIds.size() > 0){
            setmealGroupMapper.deleteBySetmealId(setmeal.getId());
            for (Integer checkGroupId : checkGroupIds) {
                setmealGroupMapper.insert(setmeal.getId(),checkGroupId);
            }
        }
    }

    /**
     * 根据套餐id查询套餐
     * @param id
     * @return
     */
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.pageQuery(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 根据套餐id删除套餐
     * @param id
     */
    @Transactional
    public void delete(Integer id) {
        //删除Redis中套餐图片名
        detelePictureRedisBySetmealId(id);

        setmealGroupMapper.deleteBySetmealId(id);

        setmealMapper.delete(id);
    }

    /**
     * 根据套餐id删除Redis中套餐图片url
     * @param id
     */
    private void detelePictureRedisBySetmealId(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        if (setmeal != null){
            //从url中分离出文件名并从redis中删除
            String[] split = setmeal.getImg().split("/");
            redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_DB_RESOURCES,split[split.length - 1]);
        }
    }

}
